package com.ningmengs789.live.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ningmengs789.live.R;
import com.ningmengs789.live.http.JsonBuilder;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.net.Config;
import com.ningmengs789.live.net.broadcast.BroadcastManager;
import com.ningmengs789.live.net.network.http.HttpException;
import com.ningmengs789.live.net.response.AuthResponse;
import com.ningmengs789.live.net.utils.json.JsonMananger;
import com.ningmengs789.live.net.utils.NLog;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.server.widget.ClearWriteEditText;
import com.ningmengs789.live.server.widget.LoadDialog;
import com.ningmengs789.live.utils.CheckInstalledUtil;
import com.ningmengs789.live.utils.MyCountDownTimer;
import com.ningmengs789.live.utils.UserInfoUtil;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.xinstall.XInstall;
import com.xinstall.listener.XInstallAdapter;
import com.xinstall.model.XAppData;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mCaseLL1;
    private ClearWriteEditText mAccountET1;
    private ClearWriteEditText mCodeET1;
    private Button sendCode;

    private LinearLayout mCaseLL2;
    private ClearWriteEditText mAccountET2;
    private ClearWriteEditText mPasswordET2;

    private LinearLayout mCaseLL3;
    private TextView mTitle3;
    private int type_2 = 10;//10注册 11重置密码
    private ClearWriteEditText mAccountET3;
    private ClearWriteEditText mCodeET3;
    private Button sendCode3;
    private ClearWriteEditText mPasswordET3;

    private String user_id;
    private String trtc_user_sig;
    private int info_complete;

    private String loginType = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP,
                    Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS,
                    Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
        setContentView(R.layout.activity_login);

        initView();

        XInstall.getInstallParam(new XInstallAdapter() {
            @Override
            public void onInstall(XAppData XAppData) {
                //获取渠道数据
//                String channelCode = XAppData.getChannelCode();

                //获取数据
                Map<String, String> data = XAppData.getExtraData();
                //通过链接后面携带的参数或者通过webSdk初始化传入的data值。
                String uo = data.get("uo");

                if (uo != null){
                    //uo {"from_uid":"20003","r":"1606450298"}
                    try {
                        String from_uid = new JSONObject(uo).getString("from_uid");
                        if (!TextUtils.isEmpty(from_uid)){
                            UserInfoUtil.setFromUid(from_uid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                //webSdk初始，在buttonId里面定义的按钮点击携带数据
//                String co = data.get("co");

                //获取时间戳
//                String timeSpan = XAppData.getTimeSpan();
            }
        });
    }

    private void initView() {
        setHeadVisibility(View.GONE);

        mCaseLL1 = findViewById(R.id.case_ll_1);
        mAccountET1 = findViewById(R.id.account_et_1);
        mCodeET1 = findViewById(R.id.code_et_1);
        sendCode = findViewById(R.id.code_btn_1);
        findViewById(R.id.login_btn_1).setOnClickListener(this);
        sendCode.setOnClickListener(this);
        findViewById(R.id.close_iv_1).setOnClickListener(this);
        findViewById(R.id.reg_tv_1).setOnClickListener(this);
        findViewById(R.id.ap_tv_1).setOnClickListener(this);
        findViewById(R.id.fo_tv_1).setOnClickListener(this);

        mCaseLL2 = findViewById(R.id.case_ll_2);
        mAccountET2 = findViewById(R.id.account_et_2);
        mPasswordET2 = findViewById(R.id.password_et_2);
        findViewById(R.id.login_btn_2).setOnClickListener(this);
        findViewById(R.id.close_iv_2).setOnClickListener(this);
        findViewById(R.id.reg_tv_2).setOnClickListener(this);
        findViewById(R.id.cc_tv_2).setOnClickListener(this);
        findViewById(R.id.fo_tv_2).setOnClickListener(this);

        mCaseLL3 = findViewById(R.id.case_ll_3);
        findViewById(R.id.close_iv_3).setOnClickListener(this);
        mTitle3 = findViewById(R.id.title_tv_3);
        mAccountET3 = findViewById(R.id.account_et_3);
        mCodeET3 = findViewById(R.id.code_et_3);
        sendCode3 = findViewById(R.id.code_btn_3);
        findViewById(R.id.login_btn_3).setOnClickListener(this);
        sendCode3.setOnClickListener(this);
        mPasswordET3 = findViewById(R.id.password_et_3);
        findViewById(R.id.rl_tv_3).setOnClickListener(this);

        findViewById(R.id.yonghuxieyi).setOnClickListener(this);
        findViewById(R.id.yinsizhengce).setOnClickListener(this);
        findViewById(R.id.qqLogin).setOnClickListener(this);
        findViewById(R.id.wxLogin).setOnClickListener(this);

        countriesTV1 = findViewById(R.id.countries_tv_1);
        countriesTV1.setOnClickListener(this);
        countriesTV2 = findViewById(R.id.countries_tv_2);
        countriesTV2.setOnClickListener(this);
        countriesTV3 = findViewById(R.id.countries_tv_3);
        countriesTV3.setOnClickListener(this);

        switchBtn1 = findViewById(R.id.switch_btn_1);
        switchBtn2 = findViewById(R.id.switch_btn_2);
        switchBtn3 = findViewById(R.id.switch_btn_3);
        switchBtn1.setOnClickListener(this);
        switchBtn2.setOnClickListener(this);
        switchBtn3.setOnClickListener(this);
    }

    private String type = "phone";//phone email
    private TextView countriesTV1, countriesTV2, countriesTV3;
    private TextView switchBtn1, switchBtn2, switchBtn3;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_iv_1:
                finish();
                break;
            case R.id.login_btn_1:
                String account = mAccountET1.getText().toString().trim();
                if (TextUtils.isEmpty(account)) {
                    NToast.shortToast(mContext, getString(R.string.sc_15));
                    mAccountET1.setShakeAnimation();
                    return;
                }
                String code = mCodeET1.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    NToast.shortToast(mContext, R.string.password_is_null);
                    mCodeET1.setShakeAnimation();
                    return;
                }
                LoadDialog.show(LoginActivity.this);
                String body_ = "";
                try {
                    body_ = new JsonBuilder()
                            .put("account", account)
                            .put("code", code)
                            .put("mobile_code", mobileCode)
                            .build();
                } catch (JSONException e) {
                }
                OKHttpUtils.getInstance().getRequest("app/login/codeLogin", body_, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                        LoadDialog.dismiss(LoginActivity.this);
                    }
                    @Override
                    public void onSuccess(String result) {
                        other_login(result);
                    }
                });
                break;
            case R.id.code_btn_1:
                String account_ = mAccountET1.getText().toString().trim();
                if (TextUtils.isEmpty(account_)) {
                    NToast.shortToast(mContext, getString(R.string.sc_15));
                    mAccountET1.setShakeAnimation();
                    return;
                }
                String body = "";
                try {
                    body = new JsonBuilder()
                            .put("account", account_)
                            .put("type", 1)
                            .put("mobile_code", mobileCode)
                            .build();
                } catch (JSONException e) {
                }
                OKHttpUtils.getInstance().getRequest("app/login/sendCode", body, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                    }
                    @Override
                    public void onSuccess(String result) {
                        MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000, 1000, sendCode);
                        myCountDownTimer.start();
                    }
                });
                break;
            case R.id.reg_tv_1:
            case R.id.reg_tv_2:
                mCaseLL1.setVisibility(View.GONE);
                mCaseLL2.setVisibility(View.GONE);
                mCaseLL3.setVisibility(View.VISIBLE);
                mTitle3.setText(getString(R.string.sc_9));
                type_2 = 10;
                break;
            case R.id.ap_tv_1:
                mCaseLL3.setVisibility(View.GONE);
                mCaseLL1.setVisibility(View.GONE);
                mCaseLL2.setVisibility(View.VISIBLE);
                break;
            case R.id.fo_tv_1:
            case R.id.fo_tv_2:
                mCaseLL1.setVisibility(View.GONE);
                mCaseLL2.setVisibility(View.GONE);
                mCaseLL3.setVisibility(View.VISIBLE);
                mTitle3.setText(getString(R.string.sc_13));
                type_2 = 11;
                break;


            case R.id.login_btn_2:
                String account2 = mAccountET2.getText().toString().trim();
                if (TextUtils.isEmpty(account2)) {
                    NToast.shortToast(mContext, getString(R.string.sc_15));
                    mAccountET2.setShakeAnimation();
                    return;
                }
                String password = mPasswordET2.getText().toString().trim();
                if (TextUtils.isEmpty(password)) {
                    NToast.shortToast(mContext, getString(R.string.sc_16));
                    mPasswordET2.setShakeAnimation();
                    return;
                }
                LoadDialog.show(LoginActivity.this);
                String body_2 = "";
                try {
                    body_2 = new JsonBuilder()
                            .put("account", account2)
                            .put("password", password)
                            .put("mobile_code", mobileCode)
                            .build();
                } catch (JSONException e) {
                }
                OKHttpUtils.getInstance().getRequest("app/login/passLogin", body_2, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                        LoadDialog.dismiss(LoginActivity.this);
                    }
                    @Override
                    public void onSuccess(String result) {
                        other_login(result);
                    }
                });
                break;
            case R.id.cc_tv_2:
            case R.id.close_iv_3:
            case R.id.rl_tv_3:
            case R.id.close_iv_2:
                mCaseLL1.setVisibility(View.VISIBLE);
                mCaseLL2.setVisibility(View.GONE);
                mCaseLL3.setVisibility(View.GONE);
                break;


            case R.id.code_btn_3:
                String account_3 = mAccountET3.getText().toString().trim();
                if (TextUtils.isEmpty(account_3)) {
                    NToast.shortToast(mContext, getString(R.string.sc_15));
                    mAccountET3.setShakeAnimation();
                    return;
                }
                String body3 = "";
                try {
                    body3 = new JsonBuilder()
                            .put("account", account_3)
                            .put("type", 1)
                            .put("mobile_code", mobileCode)
                            .build();
                } catch (JSONException e) {
                }
                OKHttpUtils.getInstance().getRequest("app/login/sendCode", body3, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                    }
                    @Override
                    public void onSuccess(String result) {
                        MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000, 1000, sendCode3);
                        myCountDownTimer.start();
                    }
                });
                break;
            case R.id.login_btn_3:
                String account3 = mAccountET3.getText().toString().trim();
                if (TextUtils.isEmpty(account3)) {
                    NToast.shortToast(mContext, getString(R.string.sc_15));
                    mAccountET3.setShakeAnimation();
                    return;
                }
                String password3 = mPasswordET3.getText().toString().trim();
                if (TextUtils.isEmpty(password3)) {
                    NToast.shortToast(mContext, getString(R.string.sc_16));
                    mPasswordET3.setShakeAnimation();
                    return;
                }
                String code3 = mCodeET3.getText().toString().trim();
                if (TextUtils.isEmpty(code3)) {
                    NToast.shortToast(mContext, R.string.password_is_null);
                    mCodeET3.setShakeAnimation();
                    return;
                }
                LoadDialog.show(LoginActivity.this);
                String body_3 = "";
                try {
                    body_3 = new JsonBuilder()
                            .put("account", account3)
                            .put("password", password3)
                            .put("code", code3)
                            .put("mobile_code", mobileCode)
                            .build();
                } catch (JSONException e) {
                }
                String url3;
                if (type_2 == 10){
                    url3 = "app/login/register";
                }else {
                    url3 = "app/login/findPass";
                }
                OKHttpUtils.getInstance().getRequest(url3, body_3, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                        LoadDialog.dismiss(LoginActivity.this);
                    }
                    @Override
                    public void onSuccess(String result) {
                        other_login(result);
                    }
                });
                break;

            case R.id.qqLogin:
                if (CheckInstalledUtil.isQQClientAvailable(this)) {
                    loginType = "qq";
                    shareLoginUmeng(this, SHARE_MEDIA.QQ);
                } else {
                    NToast.shortToast(this, getString(R.string.login_qq_cliend));
                }
                break;
            case R.id.wxLogin:
                if (CheckInstalledUtil.isWeChatAppInstalled(this)) {
                    loginType = "weixin";
                    shareLoginUmeng(this, SHARE_MEDIA.WEIXIN);
                } else {
                    NToast.shortToast(this, getString(R.string.login_wx_cliend));
                }
                break;
            case R.id.yonghuxieyi:
                Intent intent = new Intent(this, HtmlWebViewActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            case R.id.yinsizhengce:
                Intent intent2 = new Intent(this, HtmlWebViewActivity.class);
                intent2.putExtra("type", 1);
                startActivity(intent2);
                break;

            case R.id.countries_tv_1:
            case R.id.countries_tv_2:
            case R.id.countries_tv_3:
                startActivityForResult(new Intent(mContext, CountriesActivity.class).putExtra("MOBILE_CODE", mobileCode), 1001);
                break;
            case R.id.switch_btn_1:
            case R.id.switch_btn_2:
            case R.id.switch_btn_3:
                mAccountET1.setText("");
                mAccountET2.setText("");
                mAccountET3.setText("");
                if (type.equals("phone")){
                    type = "email";
                    switchBtn1.setText(getString(R.string.sc_14));
                    switchBtn2.setText(getString(R.string.sc_14));
                    switchBtn3.setText(getString(R.string.sc_14));
                    mAccountET1.setHint(getString(R.string.sc_12));
                    mAccountET2.setHint(getString(R.string.sc_12));
                    mAccountET3.setHint(getString(R.string.sc_12));
                    countriesTV1.setVisibility(View.GONE);
                    countriesTV2.setVisibility(View.GONE);
                    countriesTV3.setVisibility(View.GONE);
                }else {
                    type = "phone";
                    switchBtn1.setText(getString(R.string.sc_5));
                    switchBtn2.setText(getString(R.string.sc_5));
                    switchBtn3.setText(getString(R.string.sc_5));
                    mAccountET1.setHint(getString(R.string.sc_4));
                    mAccountET2.setHint(getString(R.string.sc_4));
                    mAccountET3.setHint(getString(R.string.sc_4));
                    countriesTV1.setVisibility(View.VISIBLE);
                    countriesTV2.setVisibility(View.VISIBLE);
                    countriesTV3.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    private String mobileCode = "86";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 11101) {//QQ登录回调
            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        }else if (requestCode == 1001 && resultCode == 1002){
            if (data != null){
                mobileCode = data.getStringExtra("MOBILE_CODE");
                countriesTV1.setText("+" + mobileCode);
                countriesTV2.setText("+" + mobileCode);
                countriesTV3.setText("+" + mobileCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void other_login(String data){
        if (data == null){
            LoadDialog.dismiss(this);
            return;
        }

        try {
            AuthResponse authResponse = JsonMananger.jsonToBean(data, AuthResponse.class);
            String nickName = authResponse.getUser_info().getUser_nickname();
            String portraitUri = authResponse.getUser_info().getAvatar();
            user_id = String.valueOf(authResponse.getUser_info().getUser_id());
            trtc_user_sig = authResponse.getUser_info().getTrtc_user_sig();
            String phone_number = authResponse.getUser_info().getMobile();
            String token = authResponse.getUser_info().getToken();
            info_complete = authResponse.getUser_info().getInfo_complete();

            UserInfoUtil.setMiTencentId(user_id);
            UserInfoUtil.setMiPlatformId(user_id);
            UserInfoUtil.setAvatar(portraitUri);
            UserInfoUtil.setName(nickName);
            UserInfoUtil.setSignature(trtc_user_sig);
            if (!TextUtils.isEmpty(phone_number)){
                UserInfoUtil.setPhoneNumber(phone_number);
            }
            UserInfoUtil.setToken_InfoComplete(token, info_complete);

            //StatisticalTool.getInstance().startEngine();

            if (info_complete != 0) {
                OKHttpUtils.getInstance().getRequest("app/user/getUserInfo", "", new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        LoadDialog.dismiss(LoginActivity.this);
                    }
                    @Override
                    public void onSuccess(String result) {
                        initDatas(result);
                    }
                });
            } else {
                LoadDialog.dismiss(this);
                startActivity(new Intent(LoginActivity.this, WanShanZhiLiaoActivity.class));
                finish();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            LoadDialog.dismiss(this);
        }
    }

    private void initDatas(String result) {
        if (result == null){
            LoadDialog.dismiss(LoginActivity.this);
            return;
        }
        try {
            JSONObject data = new JSONObject(result);
            UserInfoUtil.setUserInfo(
                    data.getInt("sex"),
                    data.getInt("daren_status"),
                    data.getInt("is_vip"),
                    data.getString("speech_introduction"),
                    data.getInt("auth_status"),
                    data.getString("province_name") + "," + data.getString("city_name") + "," + data.getString("district_name"),
                    data.getString("tags"),
                    data.getInt("age"),
                    data.getString("signature"),
                    data.getInt("shuxing"));

            inLogin();
        } catch (JSONException e) {
            e.printStackTrace();
            LoadDialog.dismiss(LoginActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 友盟开始授权(登入)
     */
    public void shareLoginUmeng(final Activity activity, SHARE_MEDIA share_media_type) {
        UMShareAPI.get(activity).getPlatformInfo(activity, share_media_type, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                NLog.e("TAGTAG", "onStart Authorization: ");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                //sdk是6.4.5的,但是获取值的时候用的是6.2以前的(access_token)才能获取到值,未知原因
                String uid = map.get("uid");
                String openid = map.get("openid");//微博没有
                String unionid = map.get("unionid");//微博没有
                String access_token = map.get("access_token");
                String refresh_token = map.get("refresh_token");//微信,qq,微博都没有获取到
                String expires_in = map.get("expires_in");
                String name = map.get("name");//名称
                String gender = map.get("gender");//类型
                String iconurl = map.get("iconurl");//头像地址

                int sex = 0;
                switch (gender) {
                    case "男":
                        sex = 1;
                        break;
                    case "女":
                        sex = 2;
                        break;
                }

                LoadDialog.show(LoginActivity.this);
                String body_ = "";
                try {
                    body_ = new JsonBuilder()
                            .put("app_id", loginType)
                            .put("openid", openid)
                            .put("unionid", unionid)
                            .put("access_token", access_token )
                            .put("nickname", name)
                            .put("avatar", iconurl)
                            .put("expire_time", expires_in)
                            .put("sex", sex)
                            .build();
                } catch (JSONException e) {
                }
                OKHttpUtils.getInstance().getRequest("app/login/oauth", body_, new RequestCallback() {
                    @Override
                    public void onError(int errCode, String errInfo) {
                        NToast.shortToast(mContext, errInfo);
                        LoadDialog.dismiss(LoginActivity.this);
                    }
                    @Override
                    public void onSuccess(String result) {
                        other_login(result);
                    }
                });
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Toast.makeText(activity, "Authorization failure", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                Toast.makeText(activity, "Authorization to cancel", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void inLogin(){
        XInstall.reportRegister();
        BroadcastManager.getInstance(mContext).sendBroadcast(Config.LOGIN, Config.LOGINSUCCESS);

        LoadDialog.dismiss(this);
        NToast.shortToast(mContext, R.string.login_success);

        finish();

        /*Intent intent;
        if (Const.style == 2){
            intent = new Intent(mContext, LiveHomeActivity.class);
        }else {
            intent = new Intent(mContext, HomeActivity.class);
        }
        intent.putExtra("DATA", "queryConverMsg_");
        startActivity(intent);*/
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.bottom_silent, 0);
    }

}
